package com.ibm.db2oncampus.portal.framework.beans;

import java.io.Serializable;

import javax.servlet.http.HttpSession;

import com.ibm.db2oncampus.portal.usuario.bean.PersonBean;
import com.ibm.db2oncampus.portal.usuario.domain.Person;
import com.ibm.db2oncampus.portal.usuario.service.PersonService;

public class LoginBean extends FacesBeanSupport implements Serializable {

	private PersonService personService;
	private PersonBean personBean;
	
	private String userId;
	private String password;
	
	public String getUserId() {
		return userId;
	}
	public void setUserId(String userId) {
		this.userId = userId;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public void setPersonService(PersonService personService) {
		this.personService = personService;
	}
	public PersonBean getPersonBean() {
		return personBean;
	}
	public void setPersonBean(PersonBean personBean) {
		this.personBean = personBean;
	}
	
	
	public String login() {
		Person targetUser = personService.findPersonByUserId(this.userId);
		
		if(targetUser != null) {
			if(targetUser.getPassword().equals(password)) {
				HttpSession httpSession = (HttpSession) this.getFacesContext().getExternalContext().getSession(false);
				httpSession.setAttribute("loggedUser", targetUser);
				this.getPersonBean().setPerson(targetUser);
				this.getPersonBean().setPasswordForConfirmation(targetUser.getPassword());
			} else {
				this.password = "";
				this.addError("User Id and password do not match", null);
			}
		} else {
			this.password = "";
			this.addError("No subscription found for this User Id", null);
		}
		
		return "home";
		

	}
	
}
